#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：NoBad
@File    ：view.py
@Author  ：LYP
@Date    ：2025/10/30 13:26
@description :
"""
import logging
from datetime import datetime
import json
import re
from sys import flags

from django.db.models.expressions import result
from django.http import JsonResponse
from pyexpat.errors import messages
from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from drf_spectacular.utils import extend_schema, extend_schema_view, OpenApiParameter
from django.shortcuts import get_object_or_404

from NoBad.settings.dev import IMAGE_DIR
from models.models import UserPoster, PromptTemplate, WeChatUser, ReportTemplate, ImageTemplateConfig
from tool.larg_models_tool import VolcEngineArk
from tool.permissions import IsTokenValid, IsOwnerOrAdmin
from tool.tools import CustomStatus, logger, getEnvConfig, generate_emotion_image, genterDeepImg, \
    generate_risk_advice_image
from tool.base_views import BaseViewSet
from tool.uploader_data import cos_client
from tool.utils import ApiResponse, CustomPagination
from tool.tool_wechat import genterateUnlimitedQRCode
from tool.token_tools import _redis
from django.utils.translation import gettext as _

class PromptTemplateSerializer(serializers.ModelSerializer):
    class Meta:
        model = PromptTemplate
        fields = ['id', 'name', 'template_type', 'description']


class PosterSerializerChild(serializers.ModelSerializer):
    class Meta:
        model = UserPoster
        fields = ['id', 'parent_id']


class PosterSerializer(serializers.ModelSerializer):
    """
    海报序列化器
    """
    prompt_template = PromptTemplateSerializer(source='poster_type', read_only=True)
    child_list = serializers.SerializerMethodField()

    class Meta:
        model = UserPoster
        fields = '__all__'

    def get_child_list(self, obj):
        """
        获取当前记录的所有子记录
        :param obj: 当前海报对象
        :return: 子记录列表
        """
        request = self.context.get('request')
        children = UserPoster.objects.filter(parent_id=obj.id)
        if request and hasattr(request, 'user'):
            try:
                user = WeChatUser.objects.get(id=obj.user_id)
                current_date = datetime.now().date()
                is_valid_vip = user.is_vip and (
                        not user.vip_expire_date or user.vip_expire_date.date() >= current_date
                )
                if is_valid_vip:
                    # VIP用户：将子数据的is_active_by_user设为True并保存
                    children.update(is_active_by_user="True")  # 批量更新
                    # 重新查询更新后的子数据
                    children = UserPoster.objects.filter(parent_id=obj.id)
                else:
                    # 非VIP用户：仅显示is_active_by_user=True的子数据
                    children = children.filter(is_active_by_user="True")
            except WeChatUser.DoesNotExist:
                return []
        # 使用序列化器序列化子记录
        serializer = PosterSerializer(children, many=True, context=self.context)

        return serializer.data


def safe_parse_json(data):
    """安全解析JSON，兼容已解析的字典"""
    if isinstance(data, dict):
        return data  # 如果已是字典，直接返回
    try:
        return json.loads(data)
    except (json.JSONDecodeError, TypeError):
        return {}  # 解析失败返回空字典


@extend_schema(tags=["海报管理"])
@extend_schema_view(
    list=extend_schema(
        summary="获取海报列表",
        description="返回所有海报的信息列表",
        responses={200: PosterSerializer(many=True)},
        parameters=[
            OpenApiParameter(name="name", description="海报名称", required=False),
            OpenApiParameter(name="user", description="用户ID", required=False),
            OpenApiParameter(name="poster_type", description="海报类型", required=False)
        ]
    ),
    create=extend_schema(
        summary="创建海报",
        description="创建一个新的海报",
        request=PosterSerializer,
        responses={201: PosterSerializer},
    ),
    retrieve=extend_schema(
        summary="获取海报详情",
        description="根据海报ID获取单个海报的详细信息",
        responses={200: PosterSerializer}
    ),
    update=extend_schema(
        summary="更新海报",
        description="根据海报ID更新海报信息",
        request=PosterSerializer,
        responses={200: PosterSerializer}
    ),
    partial_update=extend_schema(
        summary="部分更新海报",
        description="根据海报ID部分更新海报信息",
        request=PosterSerializer,
        responses={200: PosterSerializer}
    ),
    destroy=extend_schema(
        summary="删除海报",
        description="根据海报ID删除海报",
        responses={204: _("删除成功")}
    )
)
class PosterView(BaseViewSet):
    """
    海报列表视图 - 处理海报的增删改查
    """
    queryset = UserPoster.objects.filter(parse_type="once")
    serializer_class = PosterSerializer
    pagination_class = CustomPagination
    # permission_classes = [IsTokenValid, IsOwnerOrAdmin]
    def get_queryset(self):
        """
        重写get_queryset方法，根据查询参数进行过滤
        :return: 过滤后的queryset对象
        """
        queryset = super().get_queryset().order_by('-last_used_time')
        name = self.request.query_params.get('name')
        user = self.request.query_params.get('user')
        poster_type = self.request.query_params.get('poster_type')
        if name:
            queryset = queryset.filter(name__icontains=name)
        if user:
            queryset = queryset.filter(user=user)
        if poster_type:
            prompdData = PromptTemplate.objects.get(template_type=poster_type)
            queryset = queryset.filter(poster_type_id=prompdData.id)
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            # 使用自定义分页响应
            return self.get_paginated_response(serializer.data)
        # 如果没有分页，返回普通响应
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)

    @extend_schema(
        summary="微信用户海报记录",
        description="只传微信用户id即可",
        parameters=[
            OpenApiParameter(name="wx_id", description="微信用户ID 实际请求在body", required=False,
                             location=OpenApiParameter.QUERY),
        ],
        responses={
            200: {
                "type": "object",
                "properties": {
                    "code": {"type": "integer", "example": 200},
                    "message": {"type": "string", "example": "操作成功"}
                }
            }
        }
    )
    @action(detail=False, methods=['post'], url_path='wx_user_poster_record')
    def wx_user_poster_record(self, request):
        """
        获取用户海报记录
        :param request:
        :return:
        """
        try:
            wx_id = request.data.get("wx_id")
            # 参数校验
            if not wx_id:
                return ApiResponse(code=400, message=_("缺少用户ID参数"))
            # 检查微信用户是否存在
            try:
                user = WeChatUser.objects.get(id=wx_id)
            except WeChatUser.DoesNotExist:
                return ApiResponse(code=404, message=_("用户不存在"))
            # 获取该用户的所有海报记录
            posters = UserPoster.objects.filter(user_id=wx_id)
            # 使用PosterSerializer序列化数据
            serializer = PosterSerializer(posters, many=True)
            return ApiResponse(data=serializer.data, message=_("获取成功"))
        except Exception as e:
            logger.error(f"获取用户海报记录失败: {str(e)}")
            return ApiResponse(code=500, message=_(("获取失败: ")) + str(e))

    def create(self, request, *args, **kwargs):
        """
        重写create方法，对请求数据进行验证并创建海报
        :param request: 请求对象
        :param args: 位置参数
        :param kwargs: 关键字参数
        :return: 创建成功的海报对象
        """
        try:
            # 权限验证已由 IsTokenValid 处理
            # request.data['user'] = request.user.id
            poster_type = request.data.get('poster_type')
            file_url = request.data.get('file_url')
            token = request.headers.get("token")
            openId = _redis.getKey(token)
            user = WeChatUser.objects.get(open_id=openId)
            userId = user.id
            genterateUnlimitedQRCode(user.open_id)
        except:
            return ApiResponse(code=status.HTTP_403_FORBIDDEN, message=_("当前token已过期，请重新登录"))
        # 获取对应的提示词模板
        try:
            prompt_templates = PromptTemplate.objects.filter(template_type=poster_type)
            if prompt_templates.exists():
                prompt_template = prompt_templates.first()  # 获取第一个匹配的记录
            else:
                return Response(
                    {"error": f"{_('未找到类型为')} '{poster_type}' {_('的提示词模板')}"},
                    status=status.HTTP_400_BAD_REQUEST
                )
        except PromptTemplate.DoesNotExist:
            return Response(
                # 核心：_() 只包裹固定文本，动态变量 'poster_type' 拼接在后面
                {"error": f"{_('未找到类型为')} '{poster_type}' {_('的提示词模板')}"},
                status=status.HTTP_400_BAD_REQUEST
            )
        file_name = f"{poster_type}_{datetime.now().strftime('%y%m%d%H%M%S')}_{userId}"
        FILE_UPLOAD_PATH = getEnvConfig("FILE_UPLOAD_PATH")
        file_url_poster = f"{FILE_UPLOAD_PATH}/img/{file_name}.png"
        waiting_poster_data = {
            'user': userId,
            'poster_type': prompt_template.id,
            'content': json.dumps({}),  # 空内容占位
            'status': "waiting",  # 状态设为等待
            'created_time': datetime.now(),
            'last_used_time': datetime.now(),
            'file_name': file_name,
            'file_url': file_url_poster,
            'usage_count': 0,  # 初始值0
            'score': 0,  # 初始值0
            'images': {"url_list": json.dumps(file_url)},
            'summary': _("海报生成中..."),  # 等待状态描述
        }
        # 创建并保存等待状态记录
        serializer = self.get_serializer(data=waiting_poster_data)
        if not serializer.is_valid():
            return Response(
                {"error": f"创建等待状态海报失败：{serializer.errors}"},
                status=status.HTTP_400_BAD_REQUEST
            )
        poster_instance = serializer.save()
        try:
            Volc = VolcEngineArk(image_url_list=file_url, prompt_id=prompt_template.id)
            result = Volc.genterateFlags()
            # result= {'result': {'poster': {'count': 42, 'flags': {'内容索取': 30, '真诚度': 55, '视觉表演': 45, '身份模糊': 20},
            #                        'summary': 'TA是一个用视觉符号伪0公里运动分享存在‘运动人设’表演倾向，未直接展装、动态含表演倾向的中等风险情感对象','gender':'male'},
            #             'report': {'advise': '保持互动观察，0公里运动分享存在‘运动人设’表演倾向，未直接展0公里运动分享存在‘运动人设’表演倾向，未直接展避免过早投入情感，优先确认对方真实动机',
            #                        'advise_summary': '警惕视觉符号表演0公里运动分享存在‘运动人设’表演倾向，未直接展性，重点验证互动中的真实意图',
            #                        'danger': '幼态化头像与腮红特效0公里运动分享存在‘运动人设’表演倾向，未直接展伪装‘易掌控感’，为后续情感索取铺垫', 'detail': {
            #                     '内容表演': '10公里运动分享存在‘运动人设’表演倾向，未直0公里运动分享存在‘运动人设’表演倾向，未直接展0公里运动分享存在‘运动人设’表演倾向，未直接展接展示真实运动记录，仅用文字暗示能力，符合‘表演型人格价值预支范式’',
            #                     '视觉符号': '头像为戴帽猫幼态化编码（符合犯罪心理学‘退行性防御0公里运动分享存在‘运动人设’表演倾向，未直接展0公里运动分享存在‘运动人设’表演倾向，未直接展机制’），高频使用腮红特效（纯欲风滤镜），根据3.5亿用户行为库，此类视觉符号表演倾向账号索取倾向高4.2倍',
            #                     '身份透明': '账号ID与签名无伪装痕迹，根据32000例实锤案例，无多账号运营特征，但视觉符号策略性强导致风险提升'},
            #                        'flags': {'价值预支': 15, '情感操控': 30, '表演性视觉': 40, '责任规避': 25},
            #                        'summary': '该账号通过戴0公里运动分享存在‘运动人设’表演倾向，未直接展帽猫头像（幼态化）和腮红特效构建表演型人格，动态内容虽0公里运动分享存在‘运动人设’表演倾向，未直接展0公里运动分享存在‘运动人设’表演倾向，未直接展日常但视觉符号存在低真诚度风险，无明显物质索取倾向但需警惕互动中的情感操控，综合风险评分42分（中等风险）。'},
            #                     }
            #          }
        except Exception as e:
            return Response(
                {"error": f"生成海报失败: {str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
        try:
            try:
                parsed_data = safe_parse_json(result)
                result = parsed_data.get("result", {})
                try:
                    poster = result["poster"]  # 海报
                    report = result["report"]  # 报告
                    gender = result['poster']['gender']  # 性别
                    logger.info(f"模型识别的性别为：: {gender}")
                except KeyError:
                    result = result["result"]
                    poster = result["poster"]  # 海报
                    report = result["report"]
            except json.JSONDecodeError:
                poster_instance.status = "error"
                poster_instance.summary = _("生成海报失败")
                poster_instance.save()
                return Response(
                    {"error": _("生成海报失败: 响应结果无法解析")},
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            print(f"report：{report}")

            flags = report.get("flags", {})
            # 计算所有分数的总和与平均值
            if flags:  # 确保flags不为空
                scores = list(flags.values())  # 提取所有分数值
                total_score = sum(scores)  # 求和
                score = total_score / len(scores)  # 计算平均值（除以4）
            else:
                score = 0  # 若flags为空，默认分数为0
            summary = poster.get("summary")

            file_name = f"{poster_type}_{datetime.now().strftime('%y%m%d%H%M%S')}_{userId}"
            FILE_UPLOAD_PATH = getEnvConfig("FILE_UPLOAD_PATH")
            # 假设 result 包含了海报的相关信息
            file_url_poster = f"{FILE_UPLOAD_PATH}/img/{file_name}.png"
            poster_instance.content = json.dumps(flags)  # 注意序列化
            poster_instance.status = "waiting"  # 生成中过渡状态
            poster_instance.file_name = f"{poster_type}_{datetime.now().strftime('%y%m%d%H%M%S')}_{userId}"
            poster_instance.file_url = f"{getEnvConfig('FILE_UPLOAD_PATH')}/img/{poster_instance.file_name}.png"
            poster_instance.usage_count = score
            poster_instance.score = score
            poster_instance.summary = summary
            poster_instance.save()
            try:
                # 1、人物模型
                report_template_character = ReportTemplate.objects.filter(
                    template_type='character',  # 使用character类型
                    gender=gender,  # 用户性别匹配
                    template_belong=poster_type,  # poster_type对应template_purpose
                    min_score__lte=score,  # 分数在最小值范围内
                    max_score__gte=score,  # 分数在最大值范围内
                    is_active=True  # 模板必须是启用状态
                ).first()
                if not report_template_character:
                    report_template_character = ReportTemplate.objects.filter(
                        template_type='character',  # 默认使用character类型
                        gender=gender,  # 用户性别匹配
                        is_active=True,
                    ).first()
                # 兜底
                if not report_template_character:
                    report_template_character = ReportTemplate.objects.filter(
                        template_type='character',
                        is_active=True,
                        is_default=True
                    ).first()
            except ReportTemplate.DoesNotExist:
                report_template_character = None
                logger.error("没有找到匹配的“人物”模板")
            try:
                # 2、背景模板
                report_template_background = ReportTemplate.objects.filter(
                    template_purpose="poster",  # poster_type对应template_purpose
                    template_type='background',
                    gender=gender,  # 用户性别匹配
                    template_belong=poster_type,
                    min_score__lte=score,
                    max_score__gte=score,
                    is_active=True  # 模板必须是启用状态
                ).first()
                if not report_template_background:
                    report_template_background = ReportTemplate.objects.filter(
                        template_purpose="poster",
                        template_type='background',  # 默认使用character类型
                        gender=gender,
                        is_active=True
                    ).first()
                # 兜底
                if not report_template_background:
                    report_template_background = ReportTemplate.objects.filter(
                        template_purpose="poster",
                        template_type='background',
                        is_default=True
                    ).first()
            except ReportTemplate.DoesNotExist:
                report_template_background = None
                logger.error("没有找到匹配的“背景”模板")
            try:
                # 3、背板 模板
                report_template_backplane = ReportTemplate.objects.filter(
                    template_type='backplane',
                    gender=gender,
                    template_belong=poster_type,
                    min_score__lte=score,
                    max_score__gte=score,
                    is_active=True
                ).first()
                if not report_template_backplane:
                    report_template_backplane = ReportTemplate.objects.filter(
                        template_type='backplane',
                        gender=gender,
                        is_active=True
                    ).first()
                if not report_template_backplane:
                    report_template_backplane = ReportTemplate.objects.filter(
                        template_type='backplane',
                        is_active=True,
                        is_default=True
                    ).first()
                    logger.error("没有找到匹配的“背板”模板")
            except ReportTemplate.DoesNotExist:
                report_template_backplane = None

            try:
                # 4、报告 模板
                deep_tem_template_background = ReportTemplate.objects.filter(
                    template_purpose="report",  # poster_type对应template_purpose
                    template_type='background',
                    gender=gender,  # 用户性别匹配
                    template_belong=poster_type,
                    min_score__lte=score,
                    max_score__gte=score,
                    is_active=True  # 模板必须是启用状态
                ).first()
                # 如果没有找到匹配的模板，使用默认模板
                if not deep_tem_template_background:
                    deep_tem_template_background = ReportTemplate.objects.filter(
                        template_purpose="report",
                        template_type='background',  # 默认使用character类型
                        gender=gender,
                        is_active=True
                    ).first()
                # 兜底
                if not deep_tem_template_background:
                    deep_tem_template_background = ReportTemplate.objects.filter(
                        template_purpose="report",
                        template_type='background',
                        is_default=True
                    ).first()
            except ReportTemplate.DoesNotExist:
                deep_tem_template_background = None
                logger.error("没有找到匹配的“报告”模板")
            config = ImageTemplateConfig.objects.all().first()
            deep_name = f"deep_parse_{datetime.now().strftime('%y%m%d%H%M%S')}_{userId}"
            deep_url = f"/img/{deep_name}.png"
            # genterDeepImg(deep_url, report, deep_tem_template_background)
            generate_risk_advice_image(deep_url, report, deep_tem_template_background)
            UserPoster.objects.create(poster_type_id=prompt_template.id, created_time=datetime.now(),
                                      file_name=deep_name,
                                      file_url=f"{FILE_UPLOAD_PATH}{deep_url}", content=report,
                                      parent_id=poster_instance.id,
                                      status='done', user_id=userId, parse_type="deep")
            path = f"/img/{file_name}.png"
            generate_emotion_image(path, flags, score, summary, report_template_character,
                                   report_template_background, report_template_backplane, user, config)
            serializer = self.get_serializer(poster_instance)
            serializer.update(poster_instance, {'status': 'done'})

            return ApiResponse(serializer.data)
        except Exception as e:
            if 'serializer' in locals():
                instance = serializer.instance
                if instance:
                    serializer.update(instance, {'status': 'error'})
            serializer.update(instance, {'status': 'error'})
            UserPoster.objects.filter(user_id=userId, parse_type="deep").delete()
            return Response(
                {"error": f"保存海报信息失败: {str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    @extend_schema(
        summary="批量删除海报",
        description="根据ID列表批量删除海报",
        parameters=[
            OpenApiParameter(name="ids", description="海报ID列表，多个ID用逗号分隔", required=True, location="query")
        ],
        responses={204: "删除成功", 400: _("参数错误")}
    )
    @action(detail=False, methods=['delete'], url_path='bulk-delete')
    def bulk_delete(self, request, *args, **kwargs):
        """
        批量删除海报
        :param request: 请求对象
        :param args: 位置参数
        :param kwargs: 关键字参数
        :return: 删除结果响应
        """
        ids_param = request.query_params.get('ids')
        # 参数验证
        if not ids_param:
            return Response(
                CustomStatus.custom_message(status=CustomStatus.BAD_REQUEST, custom_msg="缺少必需的参数 'ids'"))
        try:
            # 解析ID列表
            ids = [int(id.strip()) for id in ids_param.split(',') if id.strip()]

            if not ids:
                return Response(
                    CustomStatus.custom_message(status=CustomStatus.BAD_REQUEST, custom_msg="请提供ID列表参数"))
            # 执行删除操作
            deleted_count, _ = UserPoster.objects.filter(id__in=ids).delete()
            deleted_count_1, _ = UserPoster.objects.filter(parent_id__in=ids).delete()
            return Response(
                CustomStatus.custom_message(status=CustomStatus.SUCCESS,
                                            custom_msg=f"成功删除 {deleted_count + deleted_count_1} 个海报"))
        except ValueError:
            return Response(
                CustomStatus.custom_message(status=CustomStatus.BAD_REQUEST, custom_msg="ID列表包含无效的数字"))
        except Exception as e:
            return Response(CustomStatus.custom_message(status=CustomStatus.INTERNAL_ERROR, custom_msg=str(e)))

    @extend_schema(
        summary="获取海报深度报告",
        description="根据海报ID获取详细的分析报告",
        parameters=[
            OpenApiParameter(name="posterId", description="海报ID", required=True)
        ],
        responses={200: "深度报告数据"}
    )
    @action(detail=False, methods=['get'], url_path='deep-report')
    def get_deep_report(self, request, pk=None):
        """
        获取深度解析报告
        :param request:
        :param pk:
        :return:
        """
        try:
            poster_id = request.query_params.get('posterId')
            poster = UserPoster.objects.get(id=poster_id)
            if UserPoster.objects.filter(parent_id=poster.id).exists():
                postData = UserPoster.objects.get(parent_id=poster.id)
            return Response(CustomStatus.SUCCESS.to_response({"url": postData.file_url}))
        except Exception as e:
            return Response({"error": f"获取深度报告失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @extend_schema(
        summary="使用免费次数购买深度报告",
        description="使用免费次数购买深度报告，如果已购买则直接回显",
        parameters=[
            OpenApiParameter(name="posterId", description="海报报告ID", required=True)
        ],
        responses={200: "深度报告数据"}
    )
    @action(detail=False, methods=['get'], url_path='free_report')
    def use_free_getdeep(self, request, pk=None):
        try:
            poster_id = request.query_params.get('posterId')
            poster = UserPoster.objects.get(id=poster_id)
            token = request.headers.get("token")
            openId = _redis.getKey(token)
            user = WeChatUser.objects.get(open_id=openId)
            old_allow_count = user.allow_count
            if UserPoster.objects.filter(parent_id=poster.id).exists():
                postData = UserPoster.objects.get(parent_id=poster.id)
            else:
                return ApiResponse(
                    code=status.HTTP_404_NOT_FOUND,
                    message="您深度报告不存在"
                )
            if user.is_vip is False:
                if postData.is_active_by_user != "True" and old_allow_count >0 :
                    user.allow_count = old_allow_count - 1
                    postData.is_active_by_user = "True"
                    postData.save()
                    user.save()
                elif postData.is_active_by_user == "True":
                    return Response(CustomStatus.SUCCESS.to_response({"url": postData.file_url}))
                else:
                    return Response({
                        "code": 400,
                        "url": "",
                        "message": "您已使用完免费次数，请充值或尝试拉新"
                    })
            return Response(CustomStatus.PAYSUCCESS.to_response({"url": postData.file_url}))
        except Exception as e:
            return Response({"error": f"获取深度报告失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @extend_schema(
        summary="重新生成失败海报",
        description="根据海报ID重新生成海报",
        parameters=[
            OpenApiParameter(name="posterId", description="海报ID", required=True)
        ],
        responses={200: "海报生成成功"}
    )
    @action(detail=False, methods=['post'], url_path='re-generate-poster')
    def re_generate_poster(self, request, pk=None):
        """
        :param request:
        :param pk:
        :return:
        """
        try:
            posterId = request.query_params.get("posterId")
            print(posterId)
            postData = UserPoster.objects.get(id=posterId)
            userData = WeChatUser.objects.get(id=postData.user_id)
            file_url = json.loads(postData.images["url_list"])
            prompt_id = postData.poster_type_id
            prompt_template = PromptTemplate.objects.get(id=prompt_id)
            file_name = f"{prompt_template.template_type}_{datetime.now().strftime('%y%m%d%H%M%S')}_{userData.id}"
            FILE_UPLOAD_PATH = getEnvConfig("FILE_UPLOAD_PATH")
            postData.status = "waiting"
            postData.save()
            try:
                Volc = VolcEngineArk(image_url_list=file_url, prompt_id=prompt_id)
                result = Volc.genterateFlags()
                # result = {
                #     'poster': {'flags': {'伪君子': 85, '小奶狗癖': 70, '社畜装杯': 65, '小镇废物': 60}, 'count': 60,
                #                'summary': 'TA是一个伪君子装文化人，小奶狗癖钓女，社畜装杯的中度渣'},
                #     'report': '分析时间：2025年11月11日 10:55 AM HKT\n平台：微信朋友圈\nIP属地：香港\n【六维概率雷达图】\n渣男：55% ｜ 渣女：40% ｜ 仙人跳：10% ｜ 已婚出轨：30% ｜ 阳痿早泄：45% ｜ 正常人：15%\n【大概含渣量（本次随机＋恶意揣测）】\n大概60%（±15%随机波动，最低5%）\n→ 当前等级：【轻中度装杯/绿茶】\n【17项死刑细节＋恶意联想实锤】\n意识形态撕裂：85/100（引用君子坦荡荡，大概率精分，表面正直内心算计）\n隐藏黑盒度：60/100（没拉黑痕迹，刚分手/刚出轨后洗白）\n阶层表演焦虑：75/100（签名理想主义，装低调实则夜店装杯）\n尾号001死刑：0/100（无ID尾号，无法判定）\n性变态雷达：65/100（猫头像隐藏小奶狗癖，现实PUA钓少妇）\n已婚出轨：30/100（换驾驶证，大概率已婚装单身）\n杀猪盘硬件：0/100（无酒店元素，无作案现场）\n阳痿补偿：55/100（体重轻没肌肉，30秒早泄王）\n自欺深度：70/100（装老实，现实PUA绿茶）\n地域诈骗：0/100（沈阳IP非香港，深圳人装精英）\n缓冲负分：-15（真人照，现实蹦迪王）\n男用可爱头像：70/100（猫头像隐藏小奶狗癖）\n瑶妹甜妹捞女：50/100（非瑶妹，30岁宝妈装嫩）\n重度社交沉迷：45/100（没扩列，深夜嫖娼）\n小镇做题家废物：60/100（沈阳社畜，没985，打螺丝）\n刻意表演补偿：80/100（装低调，现实开超跑）\n总住酒店牛马or渣死刑：0/100（无酒店元素）\n【含渣量总分】：约585/1000 → 随机波动后大概60%\n【5句毒舌头人身攻击点评（10类轮盘随机乱序抽5种）】\n[抖音评论区] 签名“君子坦荡荡”=现实小人长戚戚，伪君子装B犯\n[港式茶水间] 猫头像=隐藏小奶狗癖，专钓已婚少妇\n[脉脉开盒] 沈阳换驾驶证=007牛马加班狗，省房租住酒店\n[王者荣耀语音] 体重轻=30秒早泄王，阳痿补偿狂\n[小红书匿名撕] 理想主义=现实007牛马装杯，实则打螺丝\n【一句话实锤总结】\n此人大概含渣量60%（本次随机），签名装B+小奶狗癖+社畜装杯，99%是渣男阳痿狗+已婚出轨嫌疑，建议3秒拉黑+报警留案底！\n【反诈中心＋港女茶水间最终建议】\n☑ 大概20-55%：通过，但朋友圈设仅聊天＋备注“潜在渣”\n（注：实际含渣量60%触发更高等级，应直接拉黑+群嘲）'}
            except:
                return JsonResponse(
                    CustomStatus.FAIL.custom_message(status=CustomStatus.FAIL, custom_msg=f"重新生成海报失败"))
            try:
                # result = json.loads(result)
                # result = result["result"]
                parsed_data = safe_parse_json(result)
                result = parsed_data.get("result", {})
                try:
                    poster = result["poster"]  # 海报
                    report = result["report"]  # 报告
                    gender = result['poster']['gender']  # 性别
                except KeyError:
                    result = result["result"]
                    poster = result["poster"]  # 海报
                    report = result["report"]
            except json.JSONDecodeError:
                postData.status = "error"
                postData.save()
                return JsonResponse(
                    CustomStatus.FAIL.custom_message(status=CustomStatus.FAIL,
                                                     custom_msg=f"生成海报失败: 响应结果无法解析"))
            flags = poster.get("flags", {})
            # 计算所有分数的总和与平均值
            if flags:  # 确保flags不为空
                scores = list(flags.values())  # 提取所有分数值
                total_score = sum(scores)  # 求和
                score = total_score / len(scores)  # 计算平均值（除以4）
            else:
                score = 0  # 若flags为空，默认分数为0
            summary = poster.get("summary")
            poster_type = prompt_template.template_type
            user = userData
            try:
                # 1、人物模型
                report_template_character = ReportTemplate.objects.filter(
                    template_type='character',  # 使用character类型
                    gender=gender,  # 用户性别匹配
                    template_belong=poster_type,  # poster_type对应template_purpose
                    min_score__lte=score,  # 分数在最小值范围内
                    max_score__gte=score,  # 分数在最大值范围内
                    is_active=True  # 模板必须是启用状态
                ).first()
                if not report_template_character:
                    report_template_character = ReportTemplate.objects.filter(
                        template_type='character',  # 默认使用character类型
                        gender=gender,  # 用户性别匹配
                        is_active=True,
                    ).first()
                # 兜底
                if not report_template_character:
                    report_template_character = ReportTemplate.objects.filter(
                        template_type='character',
                        is_active=True,
                        is_default=True
                    ).first()
            except ReportTemplate.DoesNotExist:
                report_template_character = None
                logger.error("没有找到匹配的“人物”模板")
            try:
                # 2、背景模板
                report_template_background = ReportTemplate.objects.filter(
                    template_purpose="poster",  # poster_type对应template_purpose
                    template_type='background',
                    gender=gender,  # 用户性别匹配
                    template_belong=poster_type,
                    min_score__lte=score,
                    max_score__gte=score,
                    is_active=True  # 模板必须是启用状态
                ).first()
                if not report_template_background:
                    report_template_background = ReportTemplate.objects.filter(
                        template_purpose="poster",
                        template_type='background',  # 默认使用character类型
                        gender=gender,
                        is_active=True
                    ).first()
                # 兜底
                if not report_template_background:
                    report_template_background = ReportTemplate.objects.filter(
                        template_purpose="poster",
                        template_type='background',
                        is_default=True
                    ).first()
            except ReportTemplate.DoesNotExist:
                report_template_background = None
                logger.error("没有找到匹配的“背景”模板")
            try:
                # 3、背板 模板
                report_template_backplane = ReportTemplate.objects.filter(
                    template_type='backplane',
                    gender=gender,
                    template_belong=poster_type,
                    min_score__lte=score,
                    max_score__gte=score,
                    is_active=True
                ).first()
                if not report_template_backplane:
                    report_template_backplane = ReportTemplate.objects.filter(
                        template_type='backplane',
                        gender=gender,
                        is_active=True
                    ).first()
                if not report_template_backplane:
                    report_template_backplane = ReportTemplate.objects.filter(
                        template_type='backplane',
                        is_active=True,
                        is_default=True
                    ).first()
                    logger.error("没有找到匹配的“背板”模板")
            except ReportTemplate.DoesNotExist:
                report_template_backplane = None

            try:
                # 4、报告 模板
                deep_tem_template_background = ReportTemplate.objects.filter(
                    template_purpose="report",  # poster_type对应template_purpose
                    template_type='background',
                    gender=gender,  # 用户性别匹配
                    template_belong=poster_type,
                    min_score__lte=score,
                    max_score__gte=score,
                    is_active=True  # 模板必须是启用状态
                ).first()
                # 如果没有找到匹配的模板，使用默认模板
                if not deep_tem_template_background:
                    deep_tem_template_background = ReportTemplate.objects.filter(
                        template_purpose="report",
                        template_type='background',  # 默认使用character类型
                        gender__in=str(gender),
                        is_active=True
                    ).first()
                # 兜底
                if not deep_tem_template_background:
                    deep_tem_template_background = ReportTemplate.objects.filter(
                        template_purpose="report",
                        template_type='background',
                        is_default=True
                    ).first()
            except ReportTemplate.DoesNotExist:
                deep_tem_template_background = None
                logger.error("没有找到匹配的“报告”模板")
            if not report_template_character:
                report_template_character = ReportTemplate.objects.filter(
                    template_type='character',  # 默认使用character类型
                    is_active=True,
                    is_default=True
                ).first()
            config = ImageTemplateConfig.objects.all().first()
            deep_name = f"deep_parse_{datetime.now().strftime('%y%m%d%H%M%S')}_{userData.id}"
            deep_url = f"/img/{deep_name}.png"
            # genterDeepImg(deep_url, report, deep_tem_template_background)
            generate_risk_advice_image(deep_url, report, deep_tem_template_background)
            UserPoster.objects.create(poster_type_id=prompt_template.id, created_time=datetime.now(),
                                      file_name=deep_name,
                                      file_url=f"{FILE_UPLOAD_PATH}{deep_url}", content=report,
                                      parent_id=posterId,
                                      status='done', user_id=userData.id, parse_type="deep")
            path = f"/img/{file_name}.png"

            if not deep_tem_template_background:
                logger.warning("未找到深度报告背景模板")
                # 使用默认模板或返回错误

            if not report_template_character:
                logger.warning("未找到人物模板")

            if not config:
                logger.warning("未找到图像配置")
                return JsonResponse(
                    CustomStatus.FAIL.custom_message(
                        status=CustomStatus.FAIL,
                        custom_msg=_("重新生成海报失败,未找到图像配置")
                    )
                )

            generate_emotion_image(path, flags, score, summary, report_template_character,
                                   report_template_background, report_template_backplane, userData, config)
            postData.status = "done"
            postData.save()
            return JsonResponse(CustomStatus.custom_message(status=CustomStatus.SUCCESS, custom_msg=_("重新生成海报成功")))
        except Exception as e:
            postData.status = "error"
            postData.save()
            return JsonResponse(
                CustomStatus.FAIL.custom_message(status=CustomStatus.FAIL, custom_msg=_("重新生成海报失败%s"%e)))
